package com.qiezi.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.qiezi.R;
import com.qiezi.mvp.BaseMvpView;
import com.qiezi.mvp.BasePresenter;
import com.qiezi.mvp.PresenterDispatch;
import com.qiezi.mvp.PresenterProviders;
import com.qiezi.util.Util;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import es.dmoral.toasty.Toasty;

import static android.support.v4.content.ContextCompat.getColor;


public abstract class BaseMvpFragment<P extends BasePresenter> extends Fragment implements BaseMvpView {
    protected LayoutInflater inflater;
    protected boolean isPrepared;
    protected boolean isVisible;
    protected Activity mActivity;
    protected Context mContext;
    private PresenterDispatch mPresenterDispatch;
    private PresenterProviders mPresenterProviders;
    protected View mRootView;

    private void lazyLoad() {
        if (this.isPrepared) {
            if (!this.isVisible) {
                return;
            }
            lazyLoadData();
            this.isPrepared = false;
            return;
        }
    }

    public void complete() {
    }

    public View findViewById(@IdRes int paramInt) {
        if (this.mRootView != null) {
            return this.mRootView.findViewById(paramInt);
        }
        return null;
    }

    @LayoutRes
    public abstract int getLayoutRes();

    protected P getPresenter() {
        return this.mPresenterProviders.getPresenter(0);
    }

    public PresenterProviders getPresenterProviders() {
        return this.mPresenterProviders;
    }

    protected abstract void initData(Bundle savedInstanceState);

    protected abstract void initListener();

    protected void lazyLoadData() {
    }

    private Unbinder unbinder;

    public void onAttach(Context paramContext) {
        this.mActivity = ((Activity) paramContext);
        this.mContext = paramContext;
        super.onAttach(paramContext);
    }

    @Nullable
    public View onCreateView(LayoutInflater layoutInflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        if (mPresenterProviders == null){
            this.mPresenterProviders = PresenterProviders.inject(this);
            this.mPresenterDispatch = new PresenterDispatch(this.mPresenterProviders);
        }
        this.mPresenterDispatch.attachView(getActivity(), this);
        if (mRootView != null) {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null)
                parent.removeView(mRootView);
            if (isDestroyDetachView)
                unbinder = ButterKnife.bind(this, this.mRootView);
        } else {
            mRootView = layoutInflater.inflate(getLayoutRes(), container, false);
            mActivity = getActivity();
            mContext = mActivity;
            this.inflater = layoutInflater;
            unbinder = ButterKnife.bind(this, this.mRootView);
            initData(savedInstanceState);
            initListener();
        }
        return this.mRootView;
    }

    private boolean isDestroyDetachView = false;


    public void setDestroyDetachView(boolean destroyDetachView) {
        isDestroyDetachView = destroyDetachView;
    }

    public void onCanceled(){

    }


    @Override
    public void onDestroyView() {
        log("onDestroyView");
        onCanceled();
        super.onDestroyView();
        if (isDestroyDetachView){
            if (unbinder != null)
                unbinder.unbind();
            this.mPresenterDispatch.detachView();
        }
    }

    public void onDetach() {
        this.mActivity = null;
        this.mPresenterDispatch.detachView();
        super.onDetach();
    }

    protected void onInvisible() {
    }

    public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        this.mPresenterDispatch.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public void onViewCreated(View paramView, @Nullable Bundle paramBundle) {
        super.onViewCreated(paramView, paramBundle);
        this.mPresenterDispatch.onCreatePresenter(paramBundle);
        this.isPrepared = true;
        lazyLoad();
    }

    protected void onVisible() {
        lazyLoad();
    }

    public void setUserVisibleHint(boolean paramBoolean) {
        super.setUserVisibleHint(paramBoolean);
        if (getUserVisibleHint()) {
            this.isVisible = true;
            onVisible();
            return;
        }
        this.isVisible = false;
        onInvisible();
    }
    // 将dip值转换为px值
    public int dip2px(float dipValue){
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    // 将px值转换为dip或dp值
    public int px2dip(float pxValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    // 将px值转换为sp值
    public int px2sp(float pxValue) {
        final float fontScale = this.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    // 将sp值转换为px值
    public int sp2px(float spValue) {
        final float fontScale = this.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public void showError(String msg) {
        if (msg == null || msg.length() == 0)return;
        Toasty.normal(getActivity(), msg).show();
    }

    public void showProgressUI(boolean paramBoolean) {
    }

    public void showProgressUI(String hint) {

    }

    public void scrollToTop(){

    }



    protected boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }

    public void log(Object log){
        StringBuilder methodName = new StringBuilder();
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        for (StackTraceElement s : stackTrace){
            String name = s.getClassName();
            int last = name.indexOf("$");
            if (last > 0){
                name = name.substring(0,last);
            };
            if (name.equals(this.getClass().getName())) {
                methodName.append(s.getClassName())
                        .append(".")
                        .append(s.getMethodName())
                        .append(" 第")
                        .append(s.getLineNumber())
                        .append("行");
                break;
            }
        }
        System.out.println(methodName.toString()+" : "+log);
    }
}

